package com.itfreer.sso.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.sso.share.entity.ResponseResult;
import com.itfreer.sso.share.service.PrincipalAttributesService;
import com.itfreer.utils.HeaderUtils;
import com.itfreer.utils.json.JsonUtils;
import com.itfreer.utils.sys.SystemParameter;

/**
 * 主体属性资源接口
 */
@Component("RestPrincipalAttributesService")
public class RestPrincipalAttributesService implements PrincipalAttributesService {

	private final String getAttributesUrl = "/v1/ticketAttributes";

	@Autowired
	private SystemParameter systemParameter;

	/**
	 * 获取属性
	 *
	 * @param tgtId
	 *            TGT
	 * @param serviceDataHolder
	 *            the service to register and save in rest form
	 * @return {@link ResponseEntity} representing RESTful response
	 */
	@SuppressWarnings("unchecked")
	public final ResponseResult getAttributes(final String tgtId) {
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(systemParameter.getRemoteUrl() + getAttributesUrl + "/" + tgtId);
		Response response = target.request()
				.headers(HeaderUtils.getSysHeader(systemParameter.getsId(), systemParameter.getsPwd()))
				.buildGet().invoke();
		String msg = response.readEntity(String.class);
		Map<String, Object> map = null;
		if (msg.startsWith("{") && msg.endsWith("}")) {
			try {
				map = JsonUtils.toBean(msg, Map.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			map = new HashMap<String, Object>();
			map.put("error", msg);
		}
		ResponseResult result = new ResponseResult(response.getStatus(), map);
		response.close();
		return result;
	}
}
